const getPixels = require('get-pixels');
const fs = require('fs');
const { Worker } = require("worker_threads");
const jimp = require('jimp');
const path = require('path');


async function main(mainImgArr, imgs) {
    emptyDir('./tempImg');

    //缩小倍数
    let scale=1;
    let Narrow = 0;

    let data = [];
    let tempData={};
    for (let index = 0; index < mainImgArr.length; index++) {
        console.log('********************************************正在处理第' + (index + 1) + '张 效果图********************************************');

        const mainImg = mainImgArr[index];
        
        //是否缩放
        let image = (await jimp.read(mainImg)).clone();
        if(image.getWidth() > 400 || image.getHeight() > 400 ){
            scale=0.4;
            Narrow = 60;
        }

        await copyAndShrinkImages(mainImg,scale)
        
        let imgData = await getImgPixels('./tempImg/' + getUrlName(mainImg).name);
        

        for (let i = 0; i < imgs.length; i++) {
            const img = imgs[i];
            let name=getUrlName(img).arr[0];

            if(tempData[name]){
                let arr=tempData[name];
                let isExist=false;
                arr.forEach((o) => {
                    if(o.reliability == o.maxReliability){
                        isExist=true;
                    }
                });
                if(isExist){
                    continue;
                }
            }

            await copyAndShrinkImages(img,scale)
            let imgData2 = await getImgPixels('./tempImg/' + getUrlName(img).name);

            await runSeprateThread({
                imgData, imgData2, Narrow,
                name:name
            }).then((res) => {
                let obj=Object.assign(res,{
                    name:name,
                    TempImg:null
                });
                if(!tempData[name])tempData[name]=[];
                tempData[name].push(obj);
                
            });

        }

    }
    
    for (const key in tempData) {
        const element = tempData[key];
        let posData = { reliability: 0 };
        element.forEach((value, key) => {
            if (value.reliability > posData.reliability) {
                posData = value;
            }
        });
        data.push(posData);
    }


    // console.log('LPTEXT', data);

    fs.writeFileSync('pos.json',  JSON.stringify(data, null, 2), 'utf8');
    return data;
}





function runSeprateThread(workerData) {
    return new Promise((resolve, reject) => {
        const worker = new Worker('./seprateThread.js', { workerData });
        worker.on('message', (res) => {
            // worker.terminate();
            resolve(res);
        });
        worker.on('error', (err) => {
            console.log(err)
            reject(err)
        });
        worker.on('exit', (code) => {
            // console.log('exit code',code)
            if (code !== 0)
                reject(new Error(`Worker stopped with exit code ${code}`));
        });
    });
}

// 获取图片像素数据  
function getImgPixels(url) {
    return new Promise((resolve, reject) => {
        getPixels(url, (err, img) => {

            if (err) {
                console.log('LPTEXT 获取图片像素数据', err);
                reject(err)
                return;
            };

            // 遍历每个像素点  
            let pixels = [];
            // let pixels2 = [];
            for (let i = 0; i < img.shape[0]; i++) {
                for (let j = 0; j < img.shape[1]; j++) {
                    // 获取像素点的颜色值  
                    const color = getPixel(i, j, img);

                    if (!pixels[i]) {
                        pixels[i] = [];
                    }


                    pixels[i][j] = color.split(',');
                    // pixels2.push({
                    //     i, j, color
                    // })
                }
            }

            resolve(pixels)


        });
    })
}

function getPixel(x, y, pixels) {
    var out = [];
    var pointer = pixels.offset + (pixels.stride[0] * x) + (pixels.stride[1] * y);

    for (var i = 0; i < 4; i++) {
        out.push(pixels.data[pointer + (pixels.stride[2] * i)]);
    }

    return out.join(',');
}

function getUrlName(url) {
    let t;
    if (url.indexOf('/') != -1) {
        t = url.split('/').pop()
    } else {
        t = url.split('\\').pop()
    }
    return {
        name: t,
        arr: t.split('.')
    }
}

function emptyDir(dirPath) {
    if (fs.existsSync(dirPath)) {
        const files = fs.readdirSync(dirPath);

        for (const file of files) {
            const filePath = path.join(dirPath, file);

            if (fs.existsSync(filePath)) {
                const stat = fs.statSync(filePath);

                if (stat.isDirectory()) {
                    emptyDir(filePath);
                    fs.rmdirSync(filePath);
                } else {
                    fs.unlinkSync(filePath);
                }
            }

        }
    }
}

function copyAndShrinkImages(img,scale=0.1){
    return new Promise(async (resolve, reject) => {
        let image = (await jimp.read(img)).clone();
        // 缩小图片
        await new Promise((resolve2, reject) => {

            image.scale(scale,()=>{
                resolve2()
            });

        });

       


        // 写入缩小后的图片
        image.write('./tempImg/' + getUrlName(img).name,()=>{
            resolve(image)
        })
    })
}

module.exports = {
    main
}
